<template>
    <div class="role-container">

        <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="学生姓名" prop="studentName">
                <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="searchBtn()">搜索</el-button>
                <el-button @click="resetBtn">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="middle">
            <div class="add" style="margin-left: 20px;">
                <div class="button">
                    <el-button type="primary" :icon="Plus" @click="handleAdd()" plain>新增</el-button>
                </div>
            </div>


        </div>
        <div class="end">
            <el-table :data="tableData" row-key="studentId" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" />
                <el-table-column label="序号" prop="index">
                    <template #default="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column property="studentName" label="学生姓名" />
                <el-table-column property="idCard" label="身份证号" />
                <el-table-column property="studentSex" label="性别" />

                <el-table-column property="studentPhone" label="联系电话" />
                <el-table-column property="studentEmail" label="邮箱" />

                <el-table-column property="studentNote" label="备注" />

                <el-table-column label="状态">
                    <template #default="scope">
                        <el-button type="success" v-if="scope.row.studentStatus == 0" plain>启用</el-button>
                        <el-button type="danger" v-if="scope.row.studentStatus == 2" plain>删除</el-button>
                        <el-button type="warning" v-if="scope.row.studentStatus == 1" plain>禁用</el-button>

                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template #default="scope">


                        <el-link type="primary" @click="handleEdit(scope.row)">重置密码</el-link>
                        <br>

                        <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
                    </template>
                </el-table-column>

            </el-table>

            <!-- 分页 -->
            <div style="margin-left: 600px;">
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                        :page-sizes="[1, 2, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>

        </div>


        <!-- 新增弹窗 -->
        <el-dialog v-model="dialogVisible" :modal="true" width="800px">

            <el-form :model="formData" :rules="rules" ref="categoryForm" label-position="right">
                <el-row :gutter="20">

                    <el-col :span="12">
                        <el-form-item label="学生名称" prop="studentName" label-width="120px">
                            <el-input v-model="formData.studentName" placeholder="请输入学生姓名" clearable></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="性别" prop="studentSex" label-width="120px">
                            <el-select v-model="formData.studentSex" placeholder="请选择性别" style="width: 100%">
                                <el-option :value="'男'" label="男"></el-option>
                                <el-option :value="'女'" label="女"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="出生日期" prop="birthDate" label-width="120px">
                            <el-date-picker v-model="formData.birthDate" type="date" placeholder="选择出生日期"
                                value-format="YYYY-MM-DD" style="width: 100%">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="身份证号" prop="idCard" label-width="120px">
                            <el-input v-model="formData.idCard" placeholder="请输入身份证号码" maxlength="18" show-word-limit
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="电话号码" prop="studentPhone" label-width="120px">
                            <el-input v-model="formData.studentPhone" placeholder="请输入手机号码" clearable></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="studentEmail" label-width="120px">
                            <el-input v-model="formData.studentEmail" placeholder="请输入电子邮箱" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学生密码" label-width="120px" prop="studentPwd">
                            <el-input v-model="formData.studentPwd" :type="showPassword ? 'text' : 'password'" readonly
                                placeholder="默认密码为123456" autocomplete="off">
                                <template #append>
                                    <el-button :icon="showPassword ? View : Lock" @click="togglePasswordVisibility"
                                        style="cursor: pointer;" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <!-- <el-form-item label="校区Id" prop="studentNote" label-width="120px">
                            <el-input v-model="formData.campusId" placeholder="请输入校区Id"  :rows="1" disabled
                                clearable></el-input>
                        </el-form-item> -->

                    </el-col>
                </el-row>
                <el-col :span="12">
                    <el-form-item label="学生备注" prop="studentNote" label-width="120px">
                        <el-input v-model="formData.studentNote" placeholder="请输入备注信息" type="textarea" :rows="1"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCanle">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>


        <el-dialog v-model="deleteDialog" title="Tips" width="500">
            <span>确认要删除吗？</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="deleteDialog = false">取消</el-button>
                    <el-button type="primary" @click="deleteConfirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>


</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Calendar, Search, Edit, RefreshRight, Delete, Lock, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { selectAllStudent, addStudent, resetPwd, deleteStudent } from '@/api/Student'
import { selectAllCourse } from '@/api/class'

//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true)
const multiple = ref(true)
const total = ref(10);
const dialogVisible = ref(false)

const selected = ref("add");
//是否禁用表单
const disabled = ref(false)
const selectRow = ref([]);
const deleteDialog = ref(false)
const deleteRow = ref([])
const courseList = ref([])
const categoryList = ref([])

// 控制密码显示状态
const showPassword = ref(false);

// 切换密码可见性
const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value;
};

onMounted(async () => {
    // await selectAllCourseList();
    await getStudentList();

})
//查询参数
const queryParams = ref({
    studentName: '',   //学生姓名

    pageNum: 1,
    pageSize: 2,
    campusId: 1,


})

// 表单参数
var formData = ref({
    studentId: '',
    studentName: '',
    studentSex: '',
    birthDate: '',
    idCard: '',
    studentPhone: '',
    studentEmail: '',
    studentPwd: '123456',
    studentNote: '',
    campusId: 1
})

//表格参数
const tableData = ref([])

//校验规则
const rules = {
    studentName: [
        { required: true, message: '请输入学生名称', trigger: 'blur' }
    ],

    birthDate: [
        { required: false, message: '请选择出生日期', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (value && new Date(value) > new Date()) {
                    callback(new Error('出生日期不能晚于今天'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    idCard: [
        { required: true, message: '身份证号不能为空', trigger: 'blur' },
        {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '请输入正确的身份证号码',
            trigger: 'blur'
        }
    ],
    studentPhone: [
        { required: true, message: '电话号码不能为空', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的11位手机号码',
            trigger: 'blur'
        }
    ],
    studentEmail: [
        { required: true, message: '邮箱不能为空', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    studentStatus: [
        { required: true, message: '请选择学生状态', trigger: 'change' }
    ]


};

//每页条数变换
function handleSizeChange(val) {
    console.log("每页" + val + "条");
    queryParams.value.pageSize = val;
    queryParams.value.pageNum = 1;
    getStudentList();


}
//每码变换
function handleCurrentChange(val) {
    console.log("第" + val + "页")
    queryParams.value.pageNum = val;
    getStudentList();
}


// 选中某一列
function handleSelectionChange(selected) {
    console.log(selected, selected.length)
    single.value = selected.length != 1
    multiple.value = selected.length == 0
    selectRow.value = selected;

}

function searchBtn() {
    queryParams.value.pageNum = 1;
    getStudentList()
}

//关闭dialog
function handleCanle() {
    dialogVisible.value = false
    // 重置表单字段
    categoryForm.value.resetFields();

    // 清除表单验证
    categoryForm.value.clearValidate();

}


// 刷新
function resetBtn() {
    queryParams.value = {

        studentName: '',
        pageNum: 1,
        pageSize: queryParams.value.pageSize,
    }

    getStudentList()
}

function handleAdd() {
    dialogVisible.value = true
}

function handleConfirm() {
    // 验证表单 xxx
    categoryForm.value.validate((valid) => {
        // 重置表单字段
        // categoryForm.value.resetFields();
        if (valid) {
            console.log(formData.value, 7878)
            addStudent(formData.value).then(res => {
                console.log(res, 1224);
                if (res.code === 500) {
                    ElMessage.error(res.message);
                } else {
                    ElMessage.success("新增成功")
                }
                getStudentList();
                dialogVisible.value = false
            })
        } else {
            // 表单验证失败，显示错误信息
            ElMessage.warning("请填写完整")
        }
    });

    // 清除表单验证
    categoryForm.value.clearValidate();

}

// 重置密码
function handleEdit(row) {
    console.log(row.studentId, 78787)
    const data = {
        studentId: row.studentId
    }
    resetPwd(data).then(res => {
        getStudentList();
    })

}

// 删除
function handleDelete(row) {
    deleteDialog.value = true;

    deleteRow.value = row
    deleteDialog.value = true;
}
function deleteConfirm() {

    deleteStudent(deleteRow.value).then(res => {
        if (res.code === 500) {
            ElMessage.error(res.message);
        } else {
            ElMessage.success("删除成功")

        }
        getStudentList()
    })
    deleteDialog.value = false;

}

async function getStudentList() {
    console.log(222)
    try {
        const res = await selectAllStudent(queryParams.value);
        console.log(res, 777)
        total.value = res.data.students.total
        tableData.value = res.data.students.records
        console.log(tableData.value, 88888)

    } catch (error) {
        console.log(error)
        console.log(1111)
    }

}



</script>

<style scoped>
.role-container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    /* background-color: antiquewhite; */
}

.middle {
    width: 100%;
    height: 8vh;
    /* background-color: antiquewhite; */
    margin-bottom: 20px;
}

.add {
    margin-top: 15px;
    margin-left: 45px;
    width: 5%;
    height: 50%;
    float: left;
}

.end {
    float: left;
    width: calc(100% - 50px);
}


/* 密码输入框样式 */
:deep(.el-input-group__append) {
    background-color: #f5f7fa;
    padding: 0 10px;
}

/* 小眼睛按钮样式 */
:deep(.el-button.el-button--default) {
    border: none;
    background: transparent;
    padding: 0;
}

/* 禁用状态下的输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
    background-color: #f5f7fa;
    color: #606266;
    cursor: not-allowed;
}

/* 密码可见时的文本样式 */
:deep(input[type="text"].el-input__inner:read-only) {
    letter-spacing: 1px;
    font-family: monospace;
}
</style>